package topic;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.concurrent.TimeoutException;

/**
 * @author wangjinqiang
 * @date 2019-08-08
 */
public class ReceiveLogsTopic {
    public static final String EXCHANGE_NAME = "topic_logs";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        final Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "topic");

        final String queue = channel.queueDeclare().getQueue();

        for (String s : Arrays.asList("kern.*", "*.critical")) {
            channel.queueBind(queue, EXCHANGE_NAME, s);
        }

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        channel.basicConsume(queue, true, (consumerTag, message) -> {
            final String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + message.getEnvelope().getRoutingKey() + "':'" + msg + "'");
        }, consumerTag -> {

        });

    }
}
